import CryptoJS from 'crypto-js'

/**
 *
 * @method encrypts
 * @description 加密数据
 * @example encrypts(data)
 * @params { unknown } data
 * @params { string } key = '1234567890000000'
 * @params { string } iv = '1234567890000000'
 * @returns boolean
 * @version v1.0.0
 * @author liuxu 2022-12-07
 *
 */

export function encrypts(
  data: string | object,
  key = '1234567890000000',
  iv = '1234567890000000'
): string {
  const string = JSON.stringify(data)
  return CryptoJS.AES.encrypt(string, CryptoJS.enc.Utf8.parse(key), {
    iv: CryptoJS.enc.Utf8.parse(iv),
    padding: CryptoJS.pad.Pkcs7,
    mode: CryptoJS.mode.CBC,
  }).toString()
}

/**
 *
 * @method decrypts
 * @description 解密数据
 * @example decrypts(data)
 * @params { unknown } data
 * @params { string } key = '1234567890000000'
 * @params { string } iv = '1234567890000000'
 * @returns boolean
 * @version v1.0.0
 * @author liuxu 2022-12-07
 *
 */

export function decrypts(
  data: string,
  key = '1234567890000000',
  iv = '1234567890000000'
): string {
  return JSON.parse(
    CryptoJS.AES.decrypt(data, CryptoJS.enc.Utf8.parse(key), {
      iv: CryptoJS.enc.Utf8.parse(iv),
      padding: CryptoJS.pad.Pkcs7,
      mode: CryptoJS.mode.CBC,
    }).toString(CryptoJS.enc.Utf8)
  )
}
